package services

import (
	"encoding/json"
	"errors"
	"gorm.io/gorm"
	"mishop/models"
	"mishop/utils"
)

type IOrderService interface {
	FindByID(orderId uint) (*models.Order, error)
	FindByUserID(page, rows int, userId uint) (*models.Pages, error)
	Create(c *models.Order) (*models.Order, error)
	Update(c *models.Order) (*models.Order, error)
	Delete(orderId int) error
}

type OrderService struct {
	model          models.IOrder
	orderItemModel models.IOrderItem
	productModel   models.IProduct
}

func (p *OrderService) Delete(orderID int) error {
	return p.model.Delete(orderID)
}

func (p *OrderService) Update(c *models.Order) (*models.Order, error) {
	//更新orderItem

	//更新order
	_, err := p.model.FindByID(c.ID)
	if err != nil && err == gorm.ErrRecordNotFound {
		return nil, errors.New("地址未找到")
	}
	return p.model.Update(c)
}

func (p *OrderService) Create(c *models.Order) (*models.Order, error) {
	//TODO 使用事务创建
	//计算价格
	for i := 0; i < len(c.OrderItems); i++ {
		//查询商品
		product, err := p.productModel.FindByID(c.OrderItems[i].ProductID)
		if err != nil {
			return nil, err
		}
		product.Content = ""//清空不需要的数据
		productJson, err := json.Marshal(product)
		if err != nil {
			return nil, err
		}
		c.OrderItems[i].ProductSnapShoot = string(productJson)
		c.OrderItems[i].OrderID = c.ID
		c.OrderItems[i].OriginalPrice = product.OriginPrice
		c.OrderItems[i].ActualPrice = product.Price
		c.OrderItems[i].OriginalTotalPrice = float32(c.OrderItems[i].Number) * product.OriginPrice
		c.OrderItems[i].ActualTotalPrice = float32(c.OrderItems[i].Number) * product.Price

		//订单价格计算
		c.OriginalTotalPrice += c.OrderItems[i].OriginalTotalPrice
		c.ActualTotalPrice += c.OrderItems[i].ActualTotalPrice
	}
	//创建order
	order, err := p.model.Create(c)
	if err != nil {
		return nil, err
	}
	return order, nil
}
func (p *OrderService) FindByID(orderId uint) (*models.Order, error) {
	return p.model.FindByID(orderId)
}

func (p *OrderService) FindByUserID(page, rows int, userId uint) (*models.Pages, error) {
	page, rows = utils.ProcessPagesEntity(page, rows)
	return p.model.FindByUserID(page, rows, userId)
}

func NewOrderService(model models.IOrder, orderItemModel models.IOrderItem, productModel models.IProduct) IOrderService {
	return &OrderService{model: model, orderItemModel: orderItemModel, productModel: productModel}
}
